<template>
  <tl-sub-page :append-to-body="true" :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1000px" @open="open" @close="close">
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="canDisable">
      <el-row>
        <el-col :span="24">
          <el-form-item label="所属里程碑" prop="milepostname" :rules="rules.validateRequire">
            <el-input v-model="model.milepostname" :disabled="true" class="tl-ref-selector">
              <el-button slot="append" type="primary" icon="el-icon-search" @click="openSdProjectMilepostDialog" v-if="!(canDisable || changePlanEndDate)"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="任务名称" prop="taskname" :rules="rules.validateRequire">
            <el-input v-model="model.taskname" :disabled="canDisable || changePlanEndDate"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="任务内容" prop="taskdetail" :rules="rules.validateRequire">
            <el-input v-model="model.taskdetail" type="textarea" :rows="4" :disabled="canDisable || changePlanEndDate"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="责任人" prop="responsible" :rules="rules.validateRequire">
            <tl-ref-stakeholder v-model="model.responsible" :initDisplayData.sync="model.responsible" fieldKey="usercode" @confirm="getsdProjectStakeData" :externalSelectedRowKeys="model.responsiblecode" title="选择任务责任人" :externalQueryParam="externalQueryParamForStakeholder" :isSingleSelect="true" :disabled="canDisable || changePlanEndDate"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="责任人工号" prop="responsiblecode" :rules="rules.validateRequire">
            <el-input v-model="model.responsiblecode" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划开始日期" prop="planstartdate" :rules="rules.validateRequire">
            <el-date-picker v-model="model.planstartdate" type="date" :disabled="canDisable || changePlanEndDate" placeholder="例：2021-01-01" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划完成日期" prop="planenddate" :rules="rules.validateRequire">
            <el-date-picker v-model="model.planenddate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" :disabled="canDisable">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <tl-feedback-line ref="feedbackRef" style="margin-top: 20px"></tl-feedback-line>
    </el-form>
    <tl-approval-history ref="history" sourceType="GpmProjectTask" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit">取消</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="!canDisable">
        <svg-icon icon-class="save" />保存
      </el-button>
      <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval || iseditapproval  && isSaved">
        <svg-icon icon-class="send" />下发任务
      </el-button>
      <!-- <el-button type="primary" @click="doDelApproval" :loading="delApprovalLoading" v-if="!disableEditSubmit" :disabled="disableDelApproval">
        <svg-icon icon-class="undo" />取消审批
      </el-button> -->
    </div>
    <tlsdProject-milepost-ref ref="sdProjectMilepostRef" title="里程碑选择" @confirm="getSdProjectMilepostData" :viewAllMilePost="viewAllMilePost" :isSingleSelect="true" :externalQueryParam="externalQueryParamForPool"></tlsdProject-milepost-ref>
    <tlsdProject-team-ref ref="sdProjectTeamRef" @confirm="getsdProjectTeamData" :isSingleSelect="true" :externalQueryParam="externalQueryParamForTeam"></tlsdProject-team-ref>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
import tlsdProjectMilepostRef from '@/views/gpm/gpmProjectMilepost/refList'
import tlsdProjectTeamRef from '@/views/gpm/gpmProjectTeam/refList'
import tlRefStakeholder from "../gpmProjectStakeholder/refList"
import tlFeedbackLine from '../gpmProjectTaskFeedback/feedbackLine'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: { tlsdProjectMilepostRef, tlsdProjectTeamRef, tlRefStakeholder, tlFeedbackLine },
  data() {
    return {
      moduleTitle: '项目任务',
      urlPrefix: '/sd/projectTask/',
      canDisable: true,
      canChange: false,
      changePlanEndDate: false,
      viewAllMilePost: false,
      isSaved: true,
      url: {
        // 额外的url
        loadPlanInfo: '/sd/projectPlan/loadPlanInfo',
        updateResponsible: 'sd/projectTask/updateResponsible',
        queryProductDeliveryNum: '/sd/projectTask/queryProductDeliveryNum'
      },
      externalQueryParamForPool: {},
      externalQueryParamForTeam: {},
      iseditapproval: false,
      // // 人员组件查询参数
      externalQueryParamForStakeholder: {
        qry_projectcode: '' // 项目编号
      }
    }
  },
  props: {
    projectinfo: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  methods: {
    assignDefaultValue() {
      if (this.isAdd) {
        this.$set(this.model, 'deptcommoncode1', this.projectinfo.deptcommoncode1)
        this.$set(this.model, 'applyorgcode', this.org.code)
        this.$set(this.model, 'applyorgname', this.org.name)
        this.$set(this.model, 'applydeptcode', this.dept.code)
        this.$set(this.model, 'applydeptname', this.dept.fullname)
        this.$set(this.model, 'applyusercode', this.user.code)
        this.$set(this.model, 'applyusername', this.user.name)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'deptcode', this.dept.code)
        this.$set(this.model, 'orgcode', this.org.code)
        this.$set(this.model, 'taskschedule', '0')
        this.$set(this.model, 'taskstate', '0')
        this.$set(this.model, 'projectid', this.projectinfo.id)
        this.$set(this.model, 'projectcode', this.projectinfo.projectcode)
        this.$set(this.model, 'projectname', this.projectinfo.projectname)
      }
    },
    // 人员选择后赋值
    addConfirm(rows, keys, values) {
      this.$set(this.model, "responsiblecode", keys)
      this.$set(this.model, "responsible", values)
    },
    /** 保存确认 */
    async beforeSubmit() {
      if (this.model.isdelivery === '1') {
        let param = {
          projectid: this.model.projectid,
          productname: this.model.productname,
          thisamount: this.model.amount
        }
        if (this.model.id) {
          param.id = this.model.id
        }
        return await getAction(this.url.queryProductDeliveryNum, param).then(async res => {
              if (res.success) {
                let delivery = res.result.delivery
                let deliveryCount = res.result.deliveryCount
                return await this.$tap.confirm('当前该产品发货数量为：' + delivery + '，共需：' + deliveryCount + '，确认保存吗?').then((_) => {
                  return true
                }).catch(() => {
                  return false
                })
              } else {
                this.$tap.alert(res.message, "warning")
                return false
              }
            })
            .catch(err => {
              this.saveLoading = false
              return false
            })
      } else {
        return true
      }
    },
    async doSubmitEdit() {
      if (!await this.beforeSubmit()) {
        return
      }
      getAction('/sd/projectMilepost/list', { qry_operatecode: this.model.milepostcode, qry_enabled: 1 }).then(res => {
        if (res.success) {
          if (new Date(res.result.dataList[0].planfinishtime).getTime() < new Date(this.model.planenddate).getTime()) {
            this.$tap.alert('任务的计划完成日期不能大于所属里程碑的计划达成日期!', 'warning')
          } else {
            this.$refs.form.validate((valid) => {
              if (valid) {
                if (this.isAdd) {
                  this.doAdd()
                  this.isSaved = false
                } else {
                    this.doEdit()
                }
              } else {
                return false
              }
            })
          }
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
      this.loadPlanInfo()
    },
    /** 执行编辑提交 */
    updateResponsible() {
      this.saveLoading = true
      let param = {
        id: this.model.id,
        responsiblecode: this.model.responsiblecode,
        responsible: this.model.responsible
      }
      putAction(this.url.updateResponsible, param)
        .then((res) => {
          if (res.success) {
            this.$tap.message(res.message, 'success')
            this.queryData(this.model.id)
            this.isAdd = false
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    loaded() {
      this.externalQueryParamForStakeholder.qry_projectcode = this.projectinfo.projectcode
      this.model.taskstate = String(this.model.taskstate)
      this.canDisable = true
      this.canChange = false
      this.changePlanEndDate = false
      let code = this.projectinfo.projectmanagercode
      // 如果任务的状态是未开始，且打开的是新增或编辑页面，允许用户对任务进行修改
      if (this.model.taskstate === '0' && !this.disableEditSubmit) {
        this.canDisable = false
        this.viewAllMilePost = true
        this.loadPlanInfo()
      } else if (this.model.taskstate === '1' && !this.disableEditSubmit && !this.isAdd) {
        // 如果任务的状态是已开始，且打开的是编辑页面，允许用户对计划完成时间进行修改
        this.canDisable = false
        this.changePlanEndDate = true
        this.loadPlanInfo()
      }
      if (this.model.id && this.model.id !== 0) {
        this.$refs.feedbackRef.queryTaskFeedbackList(this.model.id)
      }
    },
    loadPlanInfo() {
      getAction(this.url.loadPlanInfo, { milepostcode: this.model.milepostcode }).then((res) => {
        if (res.success) {
          this.iseditapproval = res.result
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    /** 提交审批 */
    doSubmitApproval() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.url.submit) {
            this.$tap.alert('请设置审批地址!', 'warning')
            return
          }
          if (!this.beforeApproval()) {
            return
          }
          this.submitLoading = true
              putAction(this.url.submit, { modelArray: this.model }).then(res => {
                if (res.success) {
                  this.$tap.message(res.message, 'success')
                  this.queryData(this.model.id)
                  this.afterApproval()
                } else {
                  this.$tap.alert(res.message, 'warning')
                }
                this.submitLoading = false
              })
        }
      })
    },
    /** 打开里程碑参照 */
    openSdProjectMilepostDialog() {
      const { projectcode } = this.model
      this.externalQueryParamForPool = {
        qry_projectcode: projectcode,
        qry_enabled: 1
      //  qry_milepoststate: 0
      }
      this.$refs.sdProjectMilepostRef.visible = true
    },
    openSdProjectTeamDialog() {
      const { projectcode } = this.model
      this.externalQueryParamForTeam = {
        qry_projectcode: projectcode,
        qry_state: 9,
        qry_appointmenttype: 1,
        qry_enabled: 1
      }
      this.$refs.sdProjectTeamRef.visible = true
    },
    /** 获取里程碑参照数据 */
    getSdProjectMilepostData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'milepostname', selectionRow.milepostname)
      this.$set(this.model, 'milepostcode', selectionRow.operatecode)
    },
    getsdProjectStakeData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'responsiblecode', selectionRow.usercode)
      this.$set(this.model, 'responsible', selectionRow.username)
    },
    getsdProjectTeamData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'responsiblecode', selectionRow.usercode)
      this.$set(this.model, 'responsible', selectionRow.username)
    },
    /** 页面打开时执行 - zhanglongfei 2019.10.18 */
    open() {
      this.model = {}
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then(_ => {
              this.assignDefaultValue()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then(_ => {
            this.loaded()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then(_ => {
            this.loaded()
          })
        }
      })
    }
  }
}
</script>

